//
//  RGMessageFindFriendVC.m
//  RedGrass
//
//  Created by wuyine on 2018/12/11.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGMeFindFriendVC.h"
#import "RGMessageFunsCell.h"
#import "RGMeInterfaceBulider.h"
#import "RGMessageContactModel.h"
#import <MJRefresh.h>
#import "DIYScanViewController.h"
#import "RGMessageInterfaceBulider.h"
#import "RGContactsViewController.h"

@interface RGMeFindFriendVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) MJRefreshHeader *mjHeader;
@property (nonatomic,strong) MJRefreshFooter *mjFooter;
@property (nonatomic,assign) NSInteger pageNum;
@property (nonatomic,strong) NSMutableArray *dataList;

@end

@implementation RGMeFindFriendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customNavBar.title = @"发现好友";
    [self showBackButton];
    _pageNum = 0;
    [self showRightButtonWithTitle:@"" imageName:@"发现好友_扫码" target:self selector:@selector(scan:)];
    self.customContentView.backgroundColor = [UIColor blackColor];
    [self.customContentView addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    [_mjHeader beginRefreshing];
    
}

- (void)scan:(UIButton *)btn {
    DIYScanViewController *vc = [[DIYScanViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadFirstPage {
    self.pageNum ++;
    HttpRequest *quest = [HttpRequest buildRequest:url_recommendUser];
    NSDictionary *params = [RGMeInterfaceBulider buildRecommendUserWithPageNumber:self.pageNum pageSize:20];
    AA_WEAK_MAKE(self) weakSelf = self;
    [quest post:params success:^(id data) {
        [weakSelf.mjHeader endRefreshing];
        NSMutableArray *tempArr = [RGMessageContactModel arrayOfModelsFromDictionaries:[data objectForKey:@"list"] error:nil];
        if(tempArr.count){
            weakSelf.dataList = tempArr;
        }else{
            weakSelf.pageNum = 0;
        }
        [weakSelf.tableView reloadData];
        
//        if (weakSelf.dataList.count < PageSize) {
//            weakSelf.mjFooter.state = MJRefreshStateNoMoreData;
//        }
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.mjHeader endRefreshing];
        [weakSelf showTextMessageWithMessage:message];
    }];
}

- (void)loadNextPage {
    self.pageNum += 1;
    HttpRequest *quest = [HttpRequest buildRequest:url_recommendUser];
    NSDictionary *params = [RGMeInterfaceBulider buildRecommendUserWithPageNumber:self.pageNum pageSize:PageSize];
    AA_WEAK_MAKE(self) weakSelf = self;
    [quest post:params success:^(id data) {
        [weakSelf.mjFooter endRefreshing];
        NSArray *list = [RGMessageContactModel arrayOfModelsFromDictionaries:[data objectForKey:@"list"] error:nil];
        if (list) {
            
            [weakSelf.dataList addObjectsFromArray:list];
            [weakSelf.tableView reloadData];
        }
//        if (list.count < PageSize) {
//            [weakSelf.mjFooter endRefreshingWithNoMoreData];
//        }
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.mjFooter endRefreshing];
        [weakSelf showTextMessageWithMessage:message];
    }];
}

-(void)actionBtnClick:(UIButton *)button{
    RGContactsViewController *vc = [[RGContactsViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RGMessageFunsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"funsCell"];
    RGMessageContactModel *findFriendModel = [self.dataList objectAtIndex:indexPath.row];
    cell.findFriendModel = findFriendModel;
    [cell setAddOrCancelBlock:^(UIButton * _Nonnull btn) {
        if (btn.isSelected) {
            HttpRequest *quest = [HttpRequest buildRequest:url_cancel];
            NSDictionary *params = [RGMessageInterfaceBulider buildUserCancel:findFriendModel.ID];
            AA_WEAK_MAKE(self) weakSelf = self;
            [quest post:params success:^(id data) {
                btn.selected = NO;
                btn.backgroundColor = UICOLOR_WITH_RGBINT(0xf73152);
            }fail:^(NSInteger code, NSString *message) {
                [weakSelf showTextMessageWithMessage:@"操作失败，请重试"];
            }];
        }else {
            HttpRequest *quest = [HttpRequest buildRequest:url_add];
            NSDictionary *params = [RGMessageInterfaceBulider buildUserAdd:findFriendModel.ID];
            AA_WEAK_MAKE(self) weakSelf = self;
            [quest post:params success:^(id data) {
                btn.selected = YES;
                btn.backgroundColor = UICOLOR_WITH_RGBINT(0x716d7f);
            }fail:^(NSInteger code, NSString *message) {
                [weakSelf showTextMessageWithMessage:@"操作失败，请重试"];
            }];
        }
    }];
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionHeader = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc]init];
    label.text = @"全部推荐";
    label.textColor = UICOLOR_WITH_RGBINT(0x999999);
    label.font = FONT(customFontName, 15);
    [sectionHeader addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(sectionHeader).mas_offset(15);
        make.bottom.mas_equalTo(sectionHeader).mas_offset(-4);
    }];
    return sectionHeader;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 90)];
        _headerView.backgroundColor = UICOLOR_WITH_RGBINT(0x000000);
        UIImageView *icon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"通讯录")];
        [_headerView addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.leading.mas_equalTo(20);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        
        UILabel *title = [[UILabel alloc] init];
        title.text = @"查看通讯录好友";
        title.font = FONT(customFontName, 16);
        title.textColor = UICOLOR_WITH_RGBINT(0xffffff);
        [_headerView addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(icon.mas_trailing).offset(12);
            make.top.equalTo(icon.mas_top).offset(2);
        }];
        
        UILabel *subTitle = [[UILabel alloc] init];
        subTitle.text = @"看看你的好友在红草视界创作了哪些作品";
        subTitle.textColor = UICOLOR_WITH_RGBINT(0x999999);
        subTitle.font = FONT(customFontName, 12);
        [_headerView addSubview:subTitle];
        [subTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(icon.mas_trailing).offset(12);
            make.bottom.equalTo(icon.mas_bottom).offset(2);
        }];
        
        UIImageView *arrow = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"更多")];
        [_headerView addSubview:arrow];
        [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-20);
            make.size.mas_equalTo(CGSizeMake(10.5, 18));
            make.centerY.mas_equalTo(0);
        }];
        
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = UICOLOR_WITH_RGBINT(0x999999);
        [_headerView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(20);
            make.trailing.mas_equalTo(-20);
            make.bottom.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];
        UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [actionBtn addTarget:self action:@selector(actionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:actionBtn];
        [actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return _headerView;
}

#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UICOLOR_WITH_RGBINT(0x000000);
        _tableView.mj_header = self.mjHeader;
//        _tableView.mj_footer = self.mjFooter;
        _tableView.tableHeaderView = self.headerView;
        [_tableView registerClass:[RGMessageFunsCell class] forCellReuseIdentifier:@"funsCell"];
    }
    return _tableView;
}

- (MJRefreshHeader *)mjHeader {
    if (!_mjHeader) {
        _mjHeader = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadFirstPage)];
    }
    return _mjHeader;
}

//- (MJRefreshFooter *)mjFooter {
//    if (!_mjFooter) {
//        _mjFooter = [MJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNextPage)];
//        _mjFooter.backgroundColor = [UIColor redColor];
//    }
//    return _mjFooter;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
